package com.qimu.saiyou.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qimu.saiyou.annotation.AuthCheck;
import com.qimu.saiyou.common.*;
import com.qimu.saiyou.constant.UserConstant;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.exception.ThrowUtils;
import com.qimu.saiyou.model.dto.comment.CommentAddRequest;
import com.qimu.saiyou.model.dto.comment.CommentQueryRequest;
import com.qimu.saiyou.model.dto.compete.CompeteQueryRequest;
import com.qimu.saiyou.model.entity.Comment;
import com.qimu.saiyou.model.entity.User;
import com.qimu.saiyou.model.vo.CommentVo;
import com.qimu.saiyou.service.CommentLikeService;
import com.qimu.saiyou.service.CommentService;
import com.qimu.saiyou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.qimu.saiyou.constant.UserConstant.ADMIN_ROLE;
import static com.qimu.saiyou.utils.NetUtils.getAddress;

/**
 * 评论
 *
 *@author: FeiXiang
 *
 */
@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Resource
    private CommentService commentService;
    @Resource
    private RedisTemplate<String, List<CommentVo>> redisTemplate;

    @Resource
    private CommentLikeService commentLikeService;
    @Resource
    private UserService userService;

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CommentVo>> getCommentListPageByPostId(@RequestBody CommentQueryRequest commentQueryRequest, HttpServletRequest request) {
        if (ObjectUtils.allNull(commentQueryRequest, commentQueryRequest.getPostId()) || commentQueryRequest.getPostId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long postId = commentQueryRequest.getPostId();
        Long parentId = commentQueryRequest.getParentId();
        int current = commentQueryRequest.getCurrent();
        int pageSize = commentQueryRequest.getPageSize();
        String sortField = commentQueryRequest.getSortField();
        String sortOrder = commentQueryRequest.getSortOrder();
        Page<CommentVo> commentVoPage = new Page<>();
        List<CommentVo> commentVoList1 = redisTemplate.opsForValue().get("commentListPageByPostId" + postId);
        if (CollUtil.isNotEmpty(commentVoList1)) {
            commentVoPage.setRecords(commentVoList1);
            return ResultUtils.success(commentVoPage);
        }
        Page<Comment> commentPage = commentService.lambdaQuery()
                .eq(Comment::getPostId, commentQueryRequest.getPostId())
                .page(new Page<>(current, pageSize));
        // 回复评论
        List<CommentVo> parentCommentList = commentPage.getRecords().stream()
                .map(commentService::getCommentVo)
                .collect(Collectors.toList());
        List<CommentVo> commentVoList = commentService.firstComment(parentCommentList);
        commentVoList = commentVoList.stream().filter(c -> c.getStatus() == 0).collect(Collectors.toList());
        commentVoPage.setTotal(commentPage.getTotal());
        commentVoPage.setSize(commentPage.getSize());
        commentVoPage.setCurrent(commentPage.getCurrent());
        commentVoPage.setRecords(commentVoList);
        redisTemplate.opsForValue().set("commentListPageByPostId" + postId, commentVoPage.getRecords(), 3, TimeUnit.MINUTES);
        return ResultUtils.success(commentVoPage);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Comment oldPost = commentService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPost.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = commentService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Comment>> listCommentByPage(@RequestBody CompeteQueryRequest competeQueryRequest) {
        long current = competeQueryRequest.getCurrent();
        long size = competeQueryRequest.getPageSize();
        Page<Comment> postPage = commentService.page(new Page<>(current, size),
                commentService.getQueryWrapper(competeQueryRequest));
        return ResultUtils.success(postPage);
    }


    @PostMapping("/sava")
    public BaseResponse<Boolean> saveComment(@RequestBody CommentAddRequest commentAddRequest, HttpServletRequest request) {
        if (ObjectUtils.anyNull(commentAddRequest, commentAddRequest.getPostId()) || commentAddRequest.getPostId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddRequest, comment);
        comment.setAddress(getAddress(request));
        comment.setUserId(userService.getLoginUser(request).getId());
        boolean save = commentService.save(comment);
        redisTemplate.delete("commentListPageByPostId" + commentAddRequest.getPostId());
        return ResultUtils.success(save);
    }

    /**
     * 下架
     *
     * @param idRequest id请求
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @AuthCheck(mustRole = ADMIN_ROLE)
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineComment(@RequestBody IdRequest idRequest) {
        if (ObjectUtils.anyNull(idRequest, idRequest.getId()) || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = idRequest.getId();
        Comment comment = commentService.getById(id);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        comment.setStatus(1);
        return ResultUtils.success(commentService.updateById(comment));
    }


    /**
     * 上架
     *
     * @param idRequest id请求
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @AuthCheck(mustRole = ADMIN_ROLE)
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineComment(@RequestBody IdRequest idRequest) {
        if (ObjectUtils.anyNull(idRequest, idRequest.getId()) || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = idRequest.getId();
        Comment comment = commentService.getById(id);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        comment.setStatus(0);
        return ResultUtils.success(commentService.updateById(comment));
    }
}
